
import paramiko
import time
import os
import os.path as osp
import sys

def copy_model_ftp(ssh_cli, sftp_cli, files, id, local_root, server_root):

    # copy file
    for f in files:
        src_path = osp.join(local_root, f)
        dst_path = osp.join(server_root, f)
        dst_dir = osp.dirname(dst_path)
        cmd = "mkdir -p {}".format(dst_dir)
        ret = ssh_cli.send(cmd + "\n")
        time.sleep(1)
        results = get_prety_text(ssh_cli.recv(1024).decode("utf8"))
        sftp_cli.put(src_path, dst_path)

    # # change id
    # cmd2 = "sed -i s/'smartbox_id = 1000'/'smartbox_id = {}'/g  {}/main.cfg".format(id, server_root)
    # ret = ssh_cli.send(cmd2 + "\n")
    # time.sleep(1)
    # results = get_prety_text(ssh_cli.recv(1024).decode("utf8"))

    return True


def get_prety_text(text):
    str1 = "\x1b[01;34m"
    str2 = "\x1b[0m"
    std_str = "\r\n"
    text = text.replace(str1, std_str).replace(str2, std_str)
    texts = text.split(std_str)
    texts = [t for t in texts if t != ""]
    return texts[1:-1]


def copy_lib_ftp(ssh_cli, sftp_cli, lib, id, local_root, server_root):
    # copy lib
    src_path = osp.join(local_root, lib)
    dst_path = osp.join(server_root, osp.basename(lib))
    dst_dir = osp.dirname(dst_path)
    cmd = "mkdir -p {} && cd {}".format(dst_dir, dst_dir)
    ret = ssh_cli.send(cmd + "\n")
    time.sleep(1)
    results = get_prety_text(ssh_cli.recv(1024).decode("utf8"))
    sftp_cli.put(src_path, dst_path)

    # tar zxf
    cmd = "tar zxf {} -C {}".format(dst_path, server_root)
    ret = ssh_cli.send(cmd + "\n")
    time.sleep(1)
    check_str = "~/service/xc_smartbox/smartbox_cpp"
    cnt = 0
    while cnt < 1000:
        time.sleep(1)
        cnt+=1
        print("waiting...", cnt)
        text = ssh_cli.recv(2048* 100).decode("utf8")
        if check_str in text: break
    
    return True

def copy_nesscery_file(ssh_cli_root, ssh_cli, sftp_cli, id, local_root, 
                        server_root, cfg_path, exe_path):
    # kill exe
    cmd = "kill -9 `pgrep smartbox` `pgrep python`"
    ret = ssh_cli_root.send(cmd + "\n")
    time.sleep(2)
    text = ssh_cli_root.recv(2048* 100).decode("utf8")

    sftp_cli.put(osp.join(local_root, cfg_path), osp.join(server_root, "cfg.json"))
    sftp_cli.put(osp.join(local_root, cfg_path.replace("/cfg.", "/lock.").replace(".json", ".t")), osp.join(server_root, "lock.t"))
    # sftp_cli.put(osp.join(local_root, "tool/remove_img.py"), osp.join(server_root, "remove_img.py"))
    sftp_cli.put(osp.join(local_root, "daemon.py"), osp.join(server_root, "daemon.py"))
    
    sftp_cli.put(osp.join(local_root, exe_path), osp.join(server_root, osp.basename(exe_path)))
    
    # chmod +x
    cmd = "chmod +x {}".format(osp.join(server_root, osp.basename(exe_path)))
    ret = ssh_cli.send(cmd + "\n")
    time.sleep(2)
    text = ssh_cli.recv(2048* 100).decode("utf8")

    return True


def remote_update(id, ip, cfg_path, exe_path, 
                local_root, server_root, 
                copy_model=False, models=[], 
                copy_lib=False, lib=None, 
                user="xunchang", password="xunchang", port=22):
    # 使用 root 更新开机启动文件
    ssh_root = paramiko.SSHClient()
    ssh_root.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    ssh_root.connect(ip, port, "root", password, timeout=10)
    ssh_cli_root = ssh_root.invoke_shell()

    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    ssh.connect(ip, port, user, password, timeout=10)
    # scp = SCPClient(ssh.get_transport())
    sftp_cli = paramiko.SFTPClient.from_transport(ssh.get_transport())
    ssh_cli = ssh.invoke_shell()

    cmd = "mkdir -p {} && cd {} && ls".format(osp.dirname(server_root), osp.dirname(server_root))
    ret = ssh_cli.send(cmd + "\n")
    time.sleep(1)
    results = get_prety_text(ssh_cli.recv(1024).decode("utf8"))
    # print("results: ", results)

    if copy_model:
        print(ip, "update copy_model_ftp... ")
        copy_model_ftp(ssh_cli, sftp_cli, models, id, local_root, server_root)

    if copy_lib:
        print(ip, "update copy_lib_ftp... ")
        copy_lib_ftp(ssh_cli, sftp_cli, lib, id, local_root, server_root)

    print(ip, "update copy_nesscery_file... ")
    copy_nesscery_file(ssh_cli_root, ssh_cli, sftp_cli, id, local_root, server_root, cfg_path, exe_path)

    # if "smartbox" not in results:
    #     print(ip, "copy model... ")

    # 关闭连接
    ssh_cli.close()
    sftp_cli.close()
    ssh.close()


    # add to /etc/ld.so.conf
    if copy_lib:
        cmd1 = "echo '{}' > /etc/ld.so.conf && \
                echo 'include /etc/ld.so.conf.d/*.conf' >> /etc/ld.so.conf && \
                ldconfig".format(osp.join(server_root, "lib"))
        print(ip, "update /etc/ld.so.conf... ")
        ret = ssh_cli_root.send(cmd1 + "\n")
        time.sleep(1)
        results = get_prety_text(ssh_cli_root.recv(1024).decode("utf8"))

        # install dependecy
        cmd2 = "cd {} && apt install libhdf5-dev libhdf5-serial-dev -y".format(server_root)
        ret = ssh_cli_root.send(cmd2 + "\n")
        time.sleep(1)
        check_str = "~/service/xc_smartbox/smartbox_cpp"
        cnt = 0
        while cnt < 60:
            time.sleep(1)
            cnt+=1
            print("waiting...", cnt)
            ssh_cli_root.settimeout(10)
            try:
                text = ssh_cli_root.recv(2048* 100).decode("utf8")
            except:
                break
            if check_str in text: break

    # echo 'cd {} && nohup ./smartbox 3 >> log.txt 2>&1' >> /etc/rc.local && \
    # echo 'cd {} && nohup ./smartbox 3 &' >> /etc/rc.local && \

    cmd1 = "echo '#!/bin/bash' > /etc/rc.local && \
            echo 'sleep 2' >> /etc/rc.local && \
            echo 'nvpmodel -m 0' >> /etc/rc.local && \
            echo 'jetson_clocks' >> /etc/rc.local && \
            echo 'echo 50 > /sys/devices/pwm-fan/target_pwm' >> /etc/rc.local && \
            echo 'cd {} && nohup python3 daemon.py &' >> /etc/rc.local && \
            echo 'exit 0' >> /etc/rc.local && \
            chmod 755 /etc/rc.local && \
            reboot".format(server_root)
    print(ip, "update /etc/rc.local... ")
    ret = ssh_cli_root.send(cmd1 + "\n")
    time.sleep(1)
    results = get_prety_text(ssh_cli_root.recv(1024).decode("utf8"))
    if not ssh_cli_root.closed: 
        ssh_cli_root.close()
    ssh_root.close()

if __name__ == "__main__":
    local_root = "/home/xc/work/code/box_cpp"


    ip_list = [
        ["1002", "192.168.100.215", "xunchang", "xunchang"],            # 江界河
        ["1003", "192.168.101.203", "xunchang", "xunchang"],            # 鲤鱼塘              1425220037659
        # ["1004", "192.168.102.102", "xunchang", "xunchang"],            # 打鱼桥
        # ["1005", "192.168.103.138", "xunchang", "xunchang"],            # 长顺1               1421021009924
        # ["1006", "192.168.104.155", "xunchang", "xunchang"],            # 长顺2                     1425220038959
        # ["1007", "192.168.105.230", "xunchang", "xunchang"],            # 长顺3                     1425220039042
        ## ["1008", "192.168.106.145", "xunchang", "xunchang"],            # 长顺4 1558 + 300    1425220039028
        # ["1009", "192.168.107.195", "xunchang", "xunchang"],            # 长顺5                     1425220038534
        # ["1010", "192.168.108.219", "xunchang", "xunchang"],            # 长顺6 1563 + 000     1425220037771
        # ["1011", "192.168.109.209", "xunchang", "xunchang"],            # 长顺7                     1425220038725
        # ["1012", "192.168.110.214", "xunchang", "xunchang"],            # 长顺8                     1425220037657
        # ["1013", "192.168.111.177", "xunchang", "xunchang"],            # 长顺9                     1425220038259
        # ["1014", "192.168.112.192", "xunchang", "xunchang"],            # 长顺10                     1425220037937
        ## ["1015", "192.168.113.109", "xunchang", "xunchang"],            # 瓮安1
        ## ["1016", "192.168.114.135", "xunchang", "xunchang"],            # 瓮安2                1425220037985
        # ["1018", "192.168.135.171", "xunchang", "xunchang"],         # 海天园      1421621001543

        ## ["1022", "192.168.115.229", "xunzhi", "xunzhi"],            # 甘巴哨            1423221006731
        ## ["1023", "192.168.116.118", "xunzhi", "xunzhi"],            #  庙村             1423221003787
        ## ["1024", "192.168.117.185", "xunzhi", "xunzhi"],            # 前所              1423221002611


        # ["2000", "192.10.11.121", "xunzhi", "xunzhi"],            # 雷山1           1423221003233
        # ["2001", "192.10.11.122", "xunzhi", "xunzhi"],            # 雷山2           1423221006547
        # ["2002", "192.10.11.123", "xunzhi", "xunzhi"],            # 雷山3           1423221002369
        # ["2003", "192.10.11.124", "xunzhi", "xunzhi"],            # 雷山4           1423221003425
        # ["2004", "192.10.11.125", "xunchang", "xunchang"],            # 雷山5           1421621055480
        # ["2005", "192.10.11.126", "xunzhi", "xunzhi"],            # 雷山6           1423221002703
        # ["2006", "192.10.14.137", "xunzhi", "xunzhi"],            # 雷山7           1423221003712
        # ["2007", "192.10.14.138", "xunzhi", "xunzhi"],            # 雷山8           1423221002367
        # ["2008", "192.10.14.139", "xunzhi", "xunzhi"],            # 雷山9           1423221002711
        # ["2009", "192.10.14.140", "xunzhi", "xunzhi"],            # 雷山10          1423221002225
        # # ["2010", "192.168.112.176", "xunzhi", "xunzhi"],            # 大唐服务区          1423221002089

        # ["2105", "192.10.4.207", "xunzhi", "xunzhi"],           # 羊排马路      1423221003489
        # ["2101", "192.10.5.213", "xunzhi", "xunzhi"],           # 平寨新村      1423221002536
        # ["2100", "192.10.6.138", "xunchang", "xunchang"],       # 东引村      1421621001543
        # ["2103", "192.10.7.168", "xunchang", "xunchang"],       # 羊排片      1421621001371
        # ["2104", "192.10.9.117", "xunchang", "xunchang"],       # 东引路观景台      1421621053904
        # # #### # ["2102", "192.168.203.205"],                   # 观景台旁      1421621000957
    ]


    copy_model = False
    models = [
        "model/cls/weather/cfg.yaml",
        "model/cls/weather/model",
        "model/cls/weather/params",
        # "model/cls/traffic_accident/cfg.yaml",
        # "model/cls/traffic_accident/model",
        # "model/cls/traffic_accident/params",

        # "model/det/fire/cfg.yaml",
        # "model/det/fire/model",
        # "model/det/fire/params",
        # "model/data/map",
        
        "model/det/car/cfg.yaml",
        "model/det/car/model",
        "model/det/car/params",
        # "model/det/car/cls/cfg.yaml",
        # "model/det/car/cls/model",
        # "model/det/car/cls/params",

        # "model/seg/sand/cfg.yaml",
        # "model/seg/sand/model",
        # "model/seg/sand/params",

        # "model/seg/slope/cfg.yaml",
        # "model/seg/slope/model",
        # "model/seg/slope/params",
    ]
    copy_lib = False
    lib = "./nano/lib.tar.gz"
    exe_path = "./nano/smartbox"

    for id, ip, user, password in ip_list:
        server_root = "/home/{}/service/xc_smartbox/smartbox_cpp".format(user)

        cfg_path = osp.join(local_root, "cfg/cfg.{}.json".format(id))
        remote_update(id, ip, cfg_path, exe_path, local_root, server_root, 
            copy_model=copy_model, models=models, 
            copy_lib=copy_lib, lib=lib, user=user, password=password
        )


"""

2101 
相机ip 192.10.5.117
NVRip 192.10.5.211
通道 1 

2103
相机ip 192.10.7.161
NVRip 192.10.7.148
通道 1

2104
相机ip 192.10.9.202
NVRip 192.10.9.208
通道 1

2105
相机ip 192.10.4.145
NVRip 192.10.4.190
通道 1


# NVR
rtsp://admin:abcd1234@192.10.5.211:554/ISAPI/streaming/channels/103
rtsp://admin:abcd1234@192.10.5.211:554/h264/ch01/main/av_stream
rtsp://admin:abcd1234@192.10.5.211:554/Streaming/Channels/101?transportmode=multicast

ok  rtsp://admin:abcd1234@192.10.5.211:554/Streaming/tracks/101?starttime=20220612t063812z&endtime=20220612t083812z
rtsp://admin:wdy123456@192.80.2.200:554/ch01/main/av_stream


# Camera
rtsp://127.0.0.1:9554/rtp/02FE724A
rtsp://admin:abcd1234@192.10.6.112:554/ISAPI/streaming/channels/101
rtsp://admin:abcd1234@192.168.230.170:554/ISAPI/streaming/channels/102
rtsp://admin:abcd1234@192.10.11.118:554/ISAPI/streaming/channels/103
rtsp://admin:abcd1234@192.10.9.202:554/ISAPI/streaming/channels/101
rtsp://admin:abcd1234@192.10.11.117:554/ch01/main/av_stream
rtsp://admin:abcd1234@192.10.9.202:554/h264/ch01/sub/av_stream

雷山1
192.10.11.101             3000
192.10.11.102             3001
192.10.11.103(录像机)
192.10.11.121(智能盒)

雷山2
192.10.11.104             3002
192.10.11.105             3003
192.10.11.106(录像机)
192.10.11.122(智能盒)

雷山3
192.10.11.107             3004
192.10.11.108             3005
192.10.11.109(录像机)
192.10.11.123(智能盒)

雷山4
192.10.11.110             3006
192.10.11.111             3007
192.10.11.112(录像机)
192.10.11.124(智能盒)

雷山5
192.10.11.113             3008
192.10.11.114             3009
192.10.11.115(录像机)
192.10.11.125(智能盒)

LED 上坡
192.168.105.100(大屏)
192.168.105.236(智能盒)

雷山6
192.10.11.116             3010
192.10.11.117             3011
192.10.11.118             3012
192.10.11.119(热成像)      3022
192.10.11.120(录像机)
192.10.11.126(智能盒)

LED 下坡
192.168.110.100(大屏)
192.168.110.113(智能盒)

雷山7
192.10.14.121             3013
192.10.14.122             3014
192.10.14.123(录像机)
192.10.14.137(智能盒)

雷山8
192.10.14.124             3015
192.10.14.125             3016
192.10.14.126(录像机)
192.10.14.138(智能盒)


雷山9
192.10.14.127             3017
192.10.14.128             3018
192.10.14.129(录像机)
192.10.14.139(智能盒)

雷山10
192.10.14.130             3019
192.10.14.131             3020
192.10.14.132(录像机)
192.10.14.140(智能盒)

雷山11
LED
192.168.112.100(大屏)
192.168.112.176(智能盒)


http://highway.xunchang.cc/files/xunchang/cameraImg/3001.jpg


free -m
swapoff -a
dd if=/dev/zero of=/var/swapfile bs=1M count=4096
mkswap /var/swapfile 
swapon /var/swapfile  
free -m


"""


"""

import os, shutil
dirs = [os.path.join("/home/xunchang/service/xc_smartbox/smartbox_cpp/log", f) for f in os.listdir("/home/xunchang/service/xc_smartbox/smartbox_cpp/log")]
for d in dirs: os.makedirs(os.path.join(d, "debug_img"), exist_ok=True)
for d in dirs: shutil.rmtree(os.path.join(d, "debug_img"))


mv /home/xc/work/code/paddle/train_data/det/car/images/2021-08-31/101/2021_8_31_7_0_37/save_error_image/* ./2021_9_9/



"""